package com.zuo.demo01.controller.admin;


import com.alibaba.fastjson.JSON;
import com.zuo.demo01.pojo.Catagory;
import com.zuo.demo01.service.CatagoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CatagoryController {


    @Autowired
    private CatagoryService catagoryService;


    @RequestMapping("/table/list/catagory")
    @ResponseBody
    public Map<String,Object> catagory_list(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit){

        Map<String,Integer> map1 = new HashMap<>();
        map1.put("startIndex",(page-1)*limit);
        map1.put("pageSize",limit);


        List<Catagory> list = catagoryService.findByPage(map1);

        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",catagoryService.count());
        map.put("data",list);
        return map;
    }

    @RequestMapping("/catagory/insert")
    @ResponseBody
    public String catagory_insert(Catagory catagory){
        Catagory byName = catagoryService.findByName(catagory);
        if(byName!=null){
            return "已经有此分类了";
        }
        catagory.setRank(0);
        int result = catagoryService.insert(catagory);
        if (result == 1) {
            return "success";
        }else{
            return "error";
        }
    }

    @RequestMapping("/catagory/update")
    @ResponseBody
    public String catagory_update(Catagory catagory){
        Catagory byName = catagoryService.findByName(catagory);
        if(byName!=null){
            return "已经有此分类了";
        }
        int result = catagoryService.update(catagory);
        if (result == 1) {
            return "success";
        }else{
            return "error";
        }
    }


    @RequestMapping("/catagory/delete")
    @ResponseBody
    public String catagory_delete(@RequestBody List<Catagory> catagories){
        Map<String,String> map = new HashMap<>();
        int result = 0;
        for (Catagory catagory:
             catagories) {
            result = catagoryService.delete(catagory.getId());
            if(result==0){
                map.put("status","error");
                break;
            }
        }
        if(result==1){
            map.put("status","success");
        }

        String remap = JSON.toJSONString(map);
        return remap;
    }






}
